package com.meiwenhui.callu;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.meiwenhui.callu.adapter.ContactCursorAdapter;
import com.meiwenhui.callu.entities.Contact;
import com.meiwenhui.callu.entities.Message;
import com.orm.androrm.DatabaseAdapter;
import com.orm.androrm.Model;
import com.orm.androrm.SelectStatement;

public class CalluActivity extends Activity {
	private static final String TAG = "CalluActivity";

	private ListView mContacts;
	private ProgressBar mProgressBar;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.contact_list);
		mContacts = (ListView) findViewById(R.id.contact_list);
		registerForContextMenu(mContacts);
		List<Map<String, Object>> contacts = new ArrayList<Map<String, Object>>();
		for (int i = 0; i < 10; i++) {
			Map<String, Object> philo = new HashMap<String, Object>();
			philo.put("contactName", "Philo");
			philo.put("contactNumber", "15258806032");
			contacts.add(philo);
		}
		// InitContactsAsyncTask initContactsTask = new InitContactsAsyncTask();
		// initContactsTask.execute("http://csdnimg.cn/www/images/csdnindex_logo.gif");

		initDb();

		// startManagingCursor(c)
		DatabaseAdapter.setDatabaseName("call_contact");
		DatabaseAdapter dbAdapter = new DatabaseAdapter(this);
		dbAdapter.open();
		SelectStatement statement = new SelectStatement();
		statement.from("contact");
		statement.select(new String[] { "mId as _id", "mName", "mPhoneNumber" });
		Cursor mCursor = dbAdapter.query(statement);

		mContacts.setAdapter(new ContactCursorAdapter(this, mCursor));

	}

	public void initDb() {
		List<Class<? extends Model>> models = new ArrayList<Class<? extends Model>>();
		models.add(Contact.class);
		models.add(Message.class);

		DatabaseAdapter.setDatabaseName("call_contact");
		DatabaseAdapter adapter = new DatabaseAdapter(getApplicationContext());
		adapter.setModels(models);

		for (int i = 0; i < 10; i++) {
			Contact c = new Contact();
			String curmil = "" + System.currentTimeMillis();
			c.getmCycle().set(curmil);
			c.getmName().set(curmil);
			c.getmPhoneNumber().set(curmil);
			c.getmTime().set(new Date());
			c.save(this);
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.callu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.memu_add:
			Intent addIntent = new Intent(this, AddContactActivity.class);
			startActivity(addIntent);
			return true;
		case R.id.memu_setting:
			// showHelp();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.context_menu, menu);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		switch (item.getItemId()) {
		case R.id.content_memu_delete:
			// editNote(info.id);
			return true;
		case R.id.content_memu_edit:
			// deleteNote(info.id);
			return true;
		default:
			return super.onContextItemSelected(item);
		}
	}

	class InitContactsAsyncTask extends AsyncTask<String, Integer, Bitmap> {// 继承AsyncTask

		@Override
		protected Bitmap doInBackground(String... params) {// 处理后台执行的任务，在后台线程执行
			publishProgress(0);// 将会调用onProgressUpdate(Integer... progress)方法
			HttpClient hc = new DefaultHttpClient();
			publishProgress(30);
			HttpGet hg = new HttpGet(params[0]);// 获取csdn的logo
			final Bitmap bm;
			try {
				HttpResponse hr = hc.execute(hg);
				bm = BitmapFactory.decodeStream(hr.getEntity().getContent());
			} catch (Exception e) {

				return null;
			}
			publishProgress(100);
			// mImageView.setImageBitmap(result); 不能在后台线程操作ui
			return bm;
		}

		protected void onProgressUpdate(Integer... progress) {// 在调用publishProgress之后被调用，在ui线程执行
			mProgressBar.setProgress(progress[0]);// 更新进度条的进度
		}

		protected void onPostExecute(Bitmap result) {// 后台任务执行完之后被调用，在ui线程执行
			if (result != null) {
				Toast.makeText(CalluActivity.this, "成功获取图片", Toast.LENGTH_LONG).show();
			} else {
				Toast.makeText(CalluActivity.this, "获取图片失败", Toast.LENGTH_LONG).show();
			}
		}

		protected void onPreExecute() {// 在
										// doInBackground(Params...)之前被调用，在ui线程执行
			mProgressBar.setProgress(0);// 进度条复位
		}

		protected void onCancelled() {// 在ui线程执行
			mProgressBar.setProgress(0);// 进度条复位
		}

	}

}